package com.category.douyijia.utils;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.category.douyijia.model.User;
import com.category.douyijia.services.UserService;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * manage the all token keys.
 * it can help us finished the 
 * SSO and permission to login.
 * @author JunfengLiu
 * @version v1.0
 * date time: 2021-7-18 18:26:00
 */
/*
 * 管理所有的token秘钥，
 * 主要包含SSO单点登录和权限登录秘钥
 * @author 刘俊沣
 * @version v1.0
 * 时间: 2021-7-18 18:26:00
 */
public class TokensManage {
	UserService userService = new UserService();
	private Encryption encryption = null;
	/**
	 * 加密方式
	 */
	private static final String KEY_ALGORITHM = "AES";
    /**
     * 默认的加密算法
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

	private static final Map<Integer, String> USER_LOGIN_IDENT_MAP = User.getUserLoginIdentMap();
	
	/**
	 * 生成用户登录秘钥
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static String getUserToken(String userId){
		if (userId != null && !(userId.equals(""))) {
			try {
				String originaltoken = ServerSocket.getHostIpV4Address().substring(2, 
						ServerSocket.getHostIpV4Address().length()-2)
						+ServerSocket.getHostMACAddress().substring(2,
						ServerSocket.getHostMACAddress().length()-2)
						+Encryption.passwordMD5(userId);
				return Encryption.passwordMD5(originaltoken);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 生成用户权限秘钥
	 * @param user
	 * @return
	 */
	public static String getUserLoginIdentToken(User user){
		if(user != null){
			String userId = user.getUserId();
			String userIdent = USER_LOGIN_IDENT_MAP.get(user.getUserLoginIdent());
			String loginToken = getUserToken(userId);
			try {
				String userLoginIdentToken=Encryption.passwordMD5(
						Encryption.passwordMD5(userId)
						+ Encryption.passwordMD5(loginToken)
						+ Encryption.passwordMD5(userIdent)
						).toString();
				return userLoginIdentToken;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
     * 随机生成密钥
     *
     * @return
     */
    public static String getAESRandomKey() {
        SecureRandom random = new SecureRandom();
        long randomKey = random.nextLong();
        return String.valueOf(randomKey);
    }
    
    /**
     * AES 加密操作
     *
     * @param content
     * 待加密内容
     * @param key
     * 加密密钥
     * @return
     * 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key) throws Exception {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = content.getBytes("utf-8");
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //通过Base64转码返回
            return byte2Base64(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return null;
    }
    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(String content, String key) {
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            //执行操作
            byte[] result = cipher.doFinal(base642Byte(content));
            return new String(result, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        try {
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            /* 
             * 此类提供加密的强随机数生成器 (RNG)，
             * 该实现在windows上每次生成的key都相同，
             * 但是在部分linux或solaris系统上则不同。
             */ 
            // SecureRandom random = new SecureRandom(key.getBytes());
            // 指定算法名称，不同的系统上生成的key是相同的。
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            //AES 要求密钥长度为 128
            kg.init(128, random);
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 字节数组转Base64编码
     *
     * @param bytes
     * 传入字节数组
     * @return
     * 返回转码结果
     */
    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    /**
     * Base64编码转字节数组
     * 
     * @param base64Key
     * 64位秘钥
     * @return
     * 字节数组
     * @throws IOException
     * IO异常
     */
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }
    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
    	String userId = "123456";
    	String userPassword = "wulixuezhe0317";
    	String userLoginToken = TokensManage.getUserToken("123456");
		System.out.println("用户登录秘钥加密结果："+userLoginToken);
		User user = new User();
		user.set("userId", userId)
			.set("userPassword", userPassword)
			.set("userLoginIden", 0);
		String userLoginIdentToken = TokensManage.getUserLoginIdentToken(user);
		System.out.println("用户身份秘钥："+userLoginIdentToken);
		String s1 ;
		try {
			String content = "hello,您好";
	        String key = TokensManage.getAESRandomKey();
	        System.out.println("原文=" + content);
			s1 = TokensManage.encrypt(content, key);
			System.out.println("加密结果=" + s1);
	        System.out.println("解密结果="+TokensManage.decrypt(s1, key));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
